from fastapi import APIRouter, UploadFile, File, HTTPException, Depends
from sqlalchemy.orm import Session

from services.face_db import FaceDBService
from deepface import DeepFace
import cv2
import numpy as np
from database import get_db

router1 = APIRouter()


@router1.post("/api/register")
async def register_face(
        name: str,
        file: UploadFile = File(...),
        db: Session = Depends(get_db)
):
    # 读取并验证图片
    contents = await file.read()
    nparr = np.frombuffer(contents, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    # 将BGR转换为RGB
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    # 人脸检测和特征提取
    try:
        embedding_obj = DeepFace.represent(
            img,
            model_name='Facenet',
            enforce_detection=True
        )
    except ValueError as e:
        raise HTTPException(400, "未检测到人脸")

    # 存储到数据库
    service = FaceDBService(db)
    person = service.create_person(name)
    embedding = embedding_obj[0]['embedding']

    service.add_face_embedding(
        str(person.id),
        embedding,
        image_path=f"storage/{person.id}.jpg"
    )
    return {"person_id": str(person.id), "message": "人脸录入成功！"}